package com.wwh.furns.web;

import com.wwh.furns.entity.Member;
import com.wwh.furns.service.MemberService;
import com.wwh.furns.service.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Albert
 * @date 2024/5/10-22:55
 * @describe
 */
public class RegisterServlet extends HttpServlet {
    private MemberService memberService = new MemberServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //System.out.println("RegisterServlet is called...");

        //接收用户注册信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        //判断用户名是否可用
        if(!memberService.isExistsUsername(username)){
            //注册
            //System.out.println("用户名 " + username + " 不存在");
            Member member = new Member(null, username, password, email);
            if(memberService.registerMember(member)){
                //System.out.println("注册成功");
                req.getRequestDispatcher("/views/member/register_ok.html").forward(req, resp);
            } else {
                //System.out.println("注册失败");
                req.getRequestDispatcher("/views/member/register_fail.html").forward(req, resp);
            }
        } else {
            //返回登录界面
            //System.out.println("用户名 " + username + " 存在");
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
        }
    }
}
